
package com.kweative.cluster.data;

import com.kweative.cluster.Cluster;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author henrik
 */
public class CMap<K,V> extends ConcurrentHashMap<K,V> implements Serializable {
	private CMap<K,V> current;
	private String id;
	private boolean changed = false;
	private int original;

	public CMap(String id) {
		super();
		this.id = id;
		current = (CMap<K, V>) Cluster.get(id,this);
		original = this.hashCode();
		if (current.hashCode() != this.hashCode()) {
			this.putAll(current);
		}

	}
	public boolean hasChanged() {
		return changed || hashCode() != original;
	}
	public void commit() {
		if (!hasChanged()) return;
		Cluster.store(id, (Serializable) this);
		original = this.hashCode();
	}
	
	@Override
	protected void finalize() throws Throwable {
		if (hasChanged())
			Logger.getAnonymousLogger().log(Level.SEVERE,"CMap was not comitted before garbage collected:" + id);
	}

}
